﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EFong.Data;
using EFong.BL.Const;

namespace EFong.BL
{
    public class FinanceBL
    {
        #region Data

        private static object syncObj = new object();

        #endregion

        #region Method

        private EFongEntities entities = EFongEntitiesManager.GetInstance();

        public void Save() 
        {
            entities.SaveChanges();
        }

        public decimal CustomerSettle(Contract.CustomerSettlement customerSettlement)
        {
            checkCustomerSettlement(customerSettlement);

            decimal 总应收金额 = 0;
            foreach (Contract.Order order in customerSettlement.OrderList)
                总应收金额 += order.Money;

            BankAccount bankAccount = null;
            if (customerSettlement.PaymentType != "现金")
            {
                bankAccount = (from ba in entities.BankAccount
                               where ba.ID == customerSettlement.BankAccount.ID
                               select ba).Single();
                bankAccount.Amount += customerSettlement.Amount;
            }
            else
            {
                decimal cash = GetCash();
                SetCash(cash + customerSettlement.Amount, false);
            }

            decimal availableIntergral = customerSettlement.Customer.Intergral;
            foreach (Contract.Order order in customerSettlement.OrderList)
            {
                availableIntergral += order.Intergral;
            }
            if (customerSettlement.Intergral > availableIntergral)
                throw new BusinessException(BusinessFail.没有足够的积分);
            decimal intergralDeduction = customerSettlement.Intergral;

            DateTime dateTime = DateTime.Now;

            Customer customer = (from c in entities.Customer
                                 where c.ID == customerSettlement.Customer.ID
                                 select c).Single();

            decimal 可支付余额 = customerSettlement.Amount + customer.Amount.Value;

            customerSettlement.OrderList = (from o in customerSettlement.OrderList
                                            orderby o.Money
                                            select o).ToList();

            foreach (Contract.Order order in customerSettlement.OrderList)
            {
                if (可支付余额 == 0 && customerSettlement.Amount != 0)
                    break;

                CustomerSettlement newCustomerSettlement = new CustomerSettlement();
                newCustomerSettlement.ID = Guid.NewGuid();
                if (bankAccount == null)
                    newCustomerSettlement.BankAccountID = null;
                else
                    newCustomerSettlement.BankAccountID = bankAccount.ID;
                newCustomerSettlement.CheckNo = customerSettlement.CheckNo;
                newCustomerSettlement.CustomerID = customerSettlement.Customer.ID;
                newCustomerSettlement.PayType = customerSettlement.PaymentType;
                newCustomerSettlement.Remark = customerSettlement.Remark;
                newCustomerSettlement.Type = order.OrderType;
                newCustomerSettlement.Ref = order.Ref;
                newCustomerSettlement.SourceID = order.ID;
                newCustomerSettlement.SettlementDate = customerSettlement.SettlementDate;
                newCustomerSettlement.CreateTime = dateTime;
                newCustomerSettlement.CreateParty = "程序";

                decimal amount = 0;
                if (order.Money < intergralDeduction)
                {
                    newCustomerSettlement.Intergral = order.Money;
                    intergralDeduction -= order.Money;
                }
                else
                {
                    newCustomerSettlement.Intergral = intergralDeduction;
                    intergralDeduction = 0;
                    if (order.Money < newCustomerSettlement.Intergral + 可支付余额)
                    {

                        amount = order.Money - newCustomerSettlement.Intergral;
                    }
                    else
                    {
                        amount = newCustomerSettlement.Intergral + 可支付余额;
                    }
                }
                可支付余额 -= amount;
                newCustomerSettlement.Amount = amount;

                settleOrder(entities, order, amount, true, dateTime, newCustomerSettlement.Intergral);

                customer.Intergral += order.Intergral;

                entities.AddToCustomerSettlement(newCustomerSettlement);
            }

            customer.Amount = 可支付余额;

            entities.SaveChanges();

            return 可支付余额;
        }

        private void checkCustomerSettlement(Contract.CustomerSettlement customerSettlement)
        {
            customerSettlement.CheckNo = customerSettlement.CheckNo.Trim();
            customerSettlement.PaymentType = customerSettlement.PaymentType.Trim();
            customerSettlement.Remark = customerSettlement.Remark.Trim();

            if (customerSettlement.PaymentType != "现金" && customerSettlement.BankAccount == null)
                throw new BusinessException(VerificationText.请输入银行账户);
            if (customerSettlement.PaymentType == string.Empty)
                throw new BusinessException(VerificationText.请输入毅丰支付方式);
            if (customerSettlement.OrderList.Count == 0)
                throw new BusinessException(VerificationText.请选择要收款的单据);
            if (customerSettlement.PostingDate == DateTime.MinValue)
                throw new BusinessException(VerificationText.请输入过账日期);
            if (customerSettlement.SettlementDate == DateTime.MinValue)
                throw new BusinessException(VerificationText.请输入结算日期);
        }

        private void settleOrder(EFongEntities entities, Contract.Order order, decimal amount, bool isCustomer, DateTime dateTime, decimal intergral)
        {
            switch (order.OrderType)
            {
                case "飞机票":
                    if (isCustomer)
                    {
                        FlightOrder flightOrder = (from fo in entities.FlightOrder
                                                   where fo.ID == order.ID
                                                   select fo).SingleOrDefault();
                        if (order.Money > amount + intergral)
                            flightOrder.CustomerStatus = "部分收款";
                        else
                            flightOrder.CustomerStatus = "已收款";
                        flightOrder.UpdateTime = dateTime;
                    }
                    else
                    {
                        FlightOrderDetail flightOrderDetail = (from fod in entities.FlightOrderDetail
                                                               where fod.ID == order.ID
                                                               select fod).SingleOrDefault();
                        if (order.Money > amount + intergral)
                            flightOrderDetail.VendorStatus = "部分支付";
                        else
                            flightOrderDetail.VendorStatus = "已支付";
                        flightOrderDetail.UpdateTime = dateTime;
                    }
                    break;
                case "火车票":
                    TrainTicketOrder trainTicketOrder = (from fo in entities.TrainTicketOrder
                                                         where fo.ID == order.ID
                                                         select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        if (isCustomer)
                            trainTicketOrder.CustomerStatus = "部分收款";
                        else
                            trainTicketOrder.VendorStatus = "部分支付";
                    else
                        if (isCustomer)
                            trainTicketOrder.CustomerStatus = "已收款";
                        else
                            trainTicketOrder.VendorStatus = "已支付";
                    trainTicketOrder.UpdateTime = dateTime;
                    break;
                case "酒店":
                    HotelBooking hotelBooking = (from fo in entities.HotelBooking
                                                 where fo.ID == order.ID
                                                 select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        if (isCustomer)
                            hotelBooking.CustomerStatus = "部分收款";
                        else
                        {
                            hotelBooking.VendorStatus = "部分支付";
                            if(hotelBooking.PaymentType.Trim() == "现付")
                                hotelBooking.CustomerStatus = "部分收款";
                        }
                    else
                        if (isCustomer)
                            hotelBooking.CustomerStatus = "已收款";
                        else
                        {
                            hotelBooking.VendorStatus = "已支付";
                            if (hotelBooking.PaymentType.Trim() == "现付")
                                hotelBooking.CustomerStatus = "已收款";
                        }
                    hotelBooking.UpdateTime = dateTime;
                    break;
                case "其他":
                    OtherBusiness otherBusiness = (from fo in entities.OtherBusiness
                                                   where fo.ID == order.ID
                                                   select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        if (isCustomer)
                            otherBusiness.CustomerStatus = "部分收款";
                        else
                            otherBusiness.VendorStatus = "部分支付";
                    else
                        if (isCustomer)
                            otherBusiness.CustomerStatus = "已收款";
                        else
                            otherBusiness.VendorStatus = "已支付";
                    otherBusiness.UpdateTime = dateTime;
                    break;
                case "自助团":
                    TouringParty touringParty = (from fo in entities.TouringParty
                                                   where fo.ID == order.ID
                                                   select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        if (isCustomer)
                            touringParty.CustomerStatus = "部分收款";
                        else
                            touringParty.VendorStatus = "部分支付";
                    else
                        if (isCustomer)
                            touringParty.CustomerStatus = "已收款";
                        else
                            touringParty.VendorStatus = "已支付";
                    touringParty.UpdateTime = dateTime;
                    break;
                case "飞机票改票":
                    FlightChange flightChange = (from fo in entities.FlightChange
                                                 where fo.ID == order.ID
                                                 select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        if (isCustomer)
                            flightChange.CustomerStatus = "部分收款";
                        else
                            flightChange.VendorStatus = "部分支付";
                    else
                        if (isCustomer)
                            flightChange.CustomerStatus = "已收款";
                        else
                            flightChange.VendorStatus = "已支付";
                    flightChange.UpdateTime = dateTime;
                    break;
                case "飞机票退票":
                    FlightReturn flightReturn = (from fo in entities.FlightReturn
                                                 where fo.ID == order.ID
                                                 select fo).SingleOrDefault();
                    if (order.Money > amount)
                        if (isCustomer)
                            flightReturn.CustomerStatus = "部分收款";
                        else
                            flightReturn.VendorStatus = "部分支付";
                    else
                        if (isCustomer)
                            flightReturn.CustomerStatus = "已收款";
                        else
                            flightReturn.VendorStatus = "已支付";
                    flightReturn.UpdateTime = dateTime;
                    break;
                case "火车票退票":
                    TrainTicketReturn trainTicketReturn = (from fo in entities.TrainTicketReturn
                                                           where fo.ID == order.ID
                                                           select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        if (isCustomer)
                            trainTicketReturn.CustomerStatus = "部分收款";
                        else
                            trainTicketReturn.VendorStatus = "部分支付";
                    else
                        if (isCustomer)
                            trainTicketReturn.CustomerStatus = "已收款";
                        else
                            trainTicketReturn.VendorStatus = "已支付";
                    trainTicketReturn.UpdateTime = dateTime;
                    break;
                case "保险单":
                    InsurancePolicy insurancePolicy = (from fo in entities.InsurancePolicy
                                                       where fo.ID == order.ID
                                                       select fo).SingleOrDefault();
                    if (order.Money > amount + intergral)
                        insurancePolicy.VendorStatus = "部分支付";
                    else
                        insurancePolicy.VendorStatus = "已支付";
                    break;
                default:
                    break;
            }
        }

        public List<Contract.飞机票支付单> GetFlightOrder()
        {
            List<Contract.飞机票支付单> resultList = new List<Contract.飞机票支付单>();

            List<Contract.飞机票支付单> flightOrderList =
                (from fod in entities.FlightOrderDetail
                 join fo in entities.FlightOrder on fod.FlightOrderID equals fo.ID
                 where fo.Status.Trim() != "已作废" &&
                       fo.CustomerStatus.Trim() != "已收款"
                 select new Contract.飞机票支付单()
                 {
                     ID = fo.ID,
                     OrderID = fo.ID,
                     DetailID = fod.ID,
                     Customer = (from c in entities.Customer
                                 where c.ID == fo.CustomerID
                                 select c.Name.Trim()).FirstOrDefault(),
                     CustomerID = fo.CustomerID,
                     Ref = fo.Ref.Trim(),
                     单据类型 = "订票",
                     Type = "飞机票",
                     //国际类型 = fo.IsInternational ? "国际航班" : "国内航班",
                     OrderUser = (from u in entities.User
                                  where u.ID == fo.OrderUserID
                                  select u.Staff.Trim()).FirstOrDefault(),
                     单据日期 = fo.OrderDate,
                     OrderDate = fo.OrderDate,
                     结算方式 = fo.CreditTerm.Trim(),
                     Money = fod.AccountReceivable,
                     总金额 = fod.AccountReceivable,
                     应付 = fod.AccountPayable,
                     利润 = fod.Profit,
                     已支付金额 = fod.Seq == 0 ? (from cs in entities.CustomerSettlement
                                             where cs.SourceID == fo.ID
                                             select cs.Amount).FirstOrDefault() : 0,
                     Currency = (from c in entities.Currency
                                 where c.ID == fo.CurrencyID
                                 select new Contract.Currency()
                                 {
                                     ID = c.ID,
                                     Name = c.Name.Trim(),
                                     Code = c.Code.Trim()
                                 }).FirstOrDefault(),
                     Intergral = fod.Intergral,
                 }).ToList();

            resultList.AddRange(flightOrderList);

            List<Contract.飞机票支付单> flightChangeList =
               (from fc in entities.FlightChange
                join fod in entities.FlightOrderDetail on fc.FlightOrderDetailID equals fod.ID
                join fo in entities.FlightOrder on fod.FlightOrderID equals fo.ID
                where fo.Status.Trim() != "已作废" &&
                      fc.CustomerStatus.Trim() != "已收款"
                select new Contract.飞机票支付单()
                {
                    ID = fc.ID,
                    OrderID = fo.ID,
                    DetailID = fod.ID,
                    Type = "飞机票改票",
                    Customer = (from c in entities.Customer
                                where c.ID == fo.CustomerID
                                select c.Name.Trim()).FirstOrDefault(),
                    CustomerID = fo.CustomerID,
                    Ref = fo.Ref.Trim(),
                    单据类型 = "改票",
                    结算方式 = fo.CreditTerm.Trim(),
                    //国际类型 = fo.IsInternational ? "国际航班" : "国内航班",
                    OrderUser = (from u in entities.User
                                 where u.ID == fc.OrderUserID
                                 select u.Staff.Trim()).FirstOrDefault(),
                    单据日期 = fo.OrderDate,
                    OrderDate = fc.OrderDate,
                    Money = fc.Price,
                    总金额 = fc.Price,
                    应付 = fc.VendorPrice,
                    利润 = fc.Profit,
                    已支付金额 = (from cs in entities.CustomerSettlement
                             where cs.SourceID == fc.ID
                             select cs.Amount).FirstOrDefault(),
                    Currency = (from c in entities.Currency
                                where c.ID == fc.CurrencyID
                                select new Contract.Currency()
                                {
                                    ID = c.ID,
                                    Name = c.Name.Trim(),
                                    Code = c.Code.Trim()
                                }).FirstOrDefault(),
                    Intergral = 0,
                }).ToList();
            resultList.AddRange(flightChangeList);

            List<Contract.飞机票支付单> flightReturnList =
              (from fr in entities.FlightReturn
               join fod in entities.FlightOrderDetail on fr.FlightOrderDetailID equals fod.ID
               join fo in entities.FlightOrder on fod.FlightOrderID equals fo.ID
               where fo.Status.Trim() != "已作废" &&
                     fr.CustomerStatus.Trim() != "已收款"
               orderby fo.ID, fod.Seq
               select new Contract.飞机票支付单()
               {
                   ID = fr.ID,
                   OrderID = fo.ID,
                   DetailID = fod.ID,
                   Seq = fod.Seq,
                   Customer = (from c in entities.Customer
                               where c.ID == fo.CustomerID
                               select c.Name.Trim()).FirstOrDefault(),
                   CustomerID = fo.CustomerID,
                   Ref = fo.Ref.Trim(),
                   单据类型 = "退票",
                   Type = "飞机票退票",
                   //国际类型 = fo.IsInternational ? "国际航班" : "国内航班",
                   OrderUser = (from u in entities.User
                                where u.ID == fr.OrderUserID
                                select u.Staff.Trim()).FirstOrDefault(),
                   单据日期 = fo.OrderDate,
                   OrderDate = fr.OrderDate,
                   结算方式 = fo.CreditTerm.Trim(),
                   Money = fr.CustomerReturnAmount,
                   总金额 = fr.CustomerReturnAmount,
                   应付 = fr.VendorReturnAmount,
                   已支付金额 = (from cs in entities.CustomerSettlement
                            where cs.SourceID == fr.ID
                            select cs.Amount).FirstOrDefault(),
                   利润 = fr.Profit,
                   Currency = (from c in entities.Currency
                               where c.ID == fr.CurrencyID
                               select new Contract.Currency()
                               {
                                   ID = c.ID,
                                   Name = c.Name.Trim(),
                                   Code = c.Code.Trim()
                               }).FirstOrDefault(),
                   Intergral = 0 - fr.Intergral,
               }).ToList();
            resultList.AddRange(flightReturnList);

            foreach (Contract.飞机票支付单 飞机票支付单 in resultList)
            {
                var flightWayList = (from fw in entities.FlightWay
                                     where fw.FlightOrderDetailID == 飞机票支付单.DetailID
                                     orderby fw.Seq
                                     select fw).ToList();
                飞机票支付单.出发日期 = flightWayList[0].DepartDate;
                StringBuilder sb = new StringBuilder();
                sb.Append(flightWayList[0].DepartLocation.Trim());

                foreach (var flightWay in flightWayList)
                {
                    sb.Append(string.Format("-{0}", flightWay.Destination.Trim()));
                }

                飞机票支付单.行程 = sb.ToString();
            }

            return (from t in resultList
                    orderby t.单据日期, t.OrderDate,t.Seq
                    select t).ToList();
        }

        public List<Contract.火车票支付单> GetTicketOrder()
        {
            List<Contract.火车票支付单> resultList = new List<Contract.火车票支付单>();

            List<Contract.火车票支付单> ticketOrderList =
                (from ttod in entities.TrainTicketOrderDetail
                 join tto in entities.TrainTicketOrder on ttod.TrainTicketOrderID equals tto.ID
                 where tto.Status.Trim() != "已作废" &&
                       tto.CustomerStatus.Trim() != "已收款"
                 select new Contract.火车票支付单()
                 {
                     ID = tto.ID,
                     OrderID = tto.ID,
                     DetailID = ttod.ID,
                     Customer = (from c in entities.Customer
                                 where c.ID == tto.CustomerID
                                 select c.Name.Trim()).FirstOrDefault(),
                     CustomerID = tto.CustomerID,
                     Ref = tto.Ref.Trim(),
                     单据类型 = "订票",
                     Type = "火车票",
                     OrderUser = (from u in entities.User
                                  where u.ID == tto.OrderUserID
                                  select u.Staff.Trim()).FirstOrDefault(),
                     单据日期 = tto.OrderDate,
                     OrderDate = tto.OrderDate,
                     Money = ttod.TotalPrice,
                     应付 = ttod.TotalPrice - ttod.Profit,
                     Currency = (from c in entities.Currency
                                 where c.ID == tto.CurrencyID
                                 select new Contract.Currency()
                                 {
                                     ID = c.ID,
                                     Name = c.Name.Trim(),
                                     Code = c.Code.Trim()
                                 }).FirstOrDefault(),
                     Intergral = 0,
                     行程 = ttod.DepartLocation + "-" + ttod.Destination,
                     利润 = ttod.Profit
                 }).ToList();
            resultList.AddRange(ticketOrderList);

            List<Guid> tempList = new List<Guid>();
            foreach (var ttod in ticketOrderList)
            {
                if (tempList.Contains(ttod.ID))
                    continue;
                ttod.已支付金额 = (from cs in entities.CustomerSettlement
                                   where cs.SourceID == ttod.ID
                                   select cs.Amount).FirstOrDefault();
            }

            List<Contract.火车票支付单> flightReturnList =
              (from ttr in entities.TrainTicketReturn
               join ttod in entities.TrainTicketOrderDetail on ttr.TrainTicketOrderDetailID equals ttod.ID
               join tto in entities.TrainTicketOrder on ttod.TrainTicketOrderID equals tto.ID
               where tto.Status.Trim() != "已作废" &&
                     ttr.CustomerStatus.Trim() != "已收款"
               select new Contract.火车票支付单()
               {
                   ID = ttr.ID,
                   OrderID = tto.ID,
                   DetailID = ttod.ID,
                   Customer = (from c in entities.Customer
                               where c.ID == tto.CustomerID
                               select c.Name.Trim()).FirstOrDefault(),
                   CustomerID = tto.CustomerID,
                   Ref = tto.Ref.Trim(),
                   单据类型 = "退票",
                   Type = "火车票退票",
                   OrderUser = (from u in entities.User
                                where u.ID == ttr.OrderUserID
                                select u.Staff.Trim()).FirstOrDefault(),
                   单据日期 = tto.OrderDate,
                   OrderDate = ttr.OrderDate,
                   Money = ttr.CustomerReturn,
                   已支付金额 = (from cs in entities.CustomerSettlement
                            where cs.SourceID == ttr.ID
                            select cs.Amount).FirstOrDefault(),
                   Currency = (from c in entities.Currency
                               where c.ID == ttr.CurrencyID
                               select new Contract.Currency()
                               {
                                   ID = c.ID,
                                   Name = c.Name.Trim(),
                                   Code = c.Code.Trim()
                               }).FirstOrDefault(),
                   Intergral = 0,
                   应付 = ttr.VendorReturn,
                   行程 = ttod.DepartLocation + "-" + ttod.Destination,
                   利润 = ttr.Profit
               }).ToList();
            resultList.AddRange(flightReturnList);

            return (from t in resultList
                    orderby t.Customer, t.单据日期, t.Ref, t.OrderDate
                    select t).ToList();
        }

        public List<Contract.酒店支付单> GetHotelOrder()
        {
            List<Contract.酒店支付单> hotelOrderList =
                (from hbd in entities.HotelBookingDetail
                 join hb in entities.HotelBooking on hbd.HotelBookingID equals hb.ID
                 where hb.Status.Trim() != "已作废" &&
                       hb.CustomerStatus.Trim() != "已收款" &&
                       hb.PaymentType.Trim() == "预付"
                 select new Contract.酒店支付单()
                 {
                     ID = hb.ID,
                     DetailID = hbd.ID,
                     Ref = hb.Ref.Trim(),
                     Type = "酒店",
                     Customer = (from c in entities.Customer
                                 where c.ID == hb.CustomerID
                                 select c.Name.Trim()).FirstOrDefault(),
                     CustomerID = hb.CustomerID,
                     OrderUser = (from u in entities.User
                                  where u.ID == hb.OrderUserID
                                  select u.Staff.Trim()).FirstOrDefault(),
                     OrderDate = hb.OrderDate,
                     Money = hbd.TotalPrice,
                     应付 = hbd.TotalVendorPrice,
                     Days = hbd.Days,
                     GuestName = hbd.GuestName.Trim(),
                     HotelName = hbd.HotelName.Trim(),
                     CheckInDate = hbd.CheckInDate,
                     RoomType = hbd.RoomType.Trim(),
                     已支付金额 = (from cs in entities.CustomerSettlement
                              where cs.SourceID == hb.ID
                              select cs.Amount).FirstOrDefault(),
                     Currency = (from c in entities.Currency
                                 where c.ID == hb.CurrencyID
                                 select new Contract.Currency()
                                 {
                                     ID = c.ID,
                                     Name = c.Name.Trim(),
                                     Code = c.Code.Trim()
                                 }).FirstOrDefault(),
                     Intergral = hbd.Intergral,
                     利润 = hb.TotalProfit,
                 }).ToList();

            return (from t in hotelOrderList
                    orderby t.Customer, t.Ref, t.CheckInDate
                    select t).ToList();
        }

        public List<Contract.其他支付单> GetOtherOrder()
        {
            List<Contract.其他支付单> otherOrderList =
                (from ob in entities.OtherBusiness
                 where ob.Status.Trim() != "已作废" &&
                       ob.CustomerStatus.Trim() != "已收款"
                 select new Contract.其他支付单()
                 {
                     ID = ob.ID,
                     Ref = ob.Ref.Trim(),
                     Type = "其他",
                     Customer = (from c in entities.Customer
                                 where c.ID == ob.CustomerID
                                 select c.Name.Trim()).FirstOrDefault(),
                     CustomerID = ob.CustomerID,
                     OrderUser = (from u in entities.User
                                  where u.ID == ob.OrderUserID
                                  select u.Staff.Trim()).FirstOrDefault(),
                     OrderDate = ob.OrderDate,
                     Money = ob.TotalPrice,
                     应付 = ob.TotalVendorPrice,
                     Project = (from p in entities.Project
                                where p.ID == ob.ProjectID
                                select p.Name.Trim()).FirstOrDefault(),
                     SubProject = (from p in entities.SubProject
                                   where p.ID == ob.SubProjectID
                                   select p.Name.Trim()).FirstOrDefault(),
                     Content = ob.Contenct.Trim(),
                     ProjectDate = ob.ProjectDate,
                     已支付金额 = (from cs in entities.CustomerSettlement
                              where cs.SourceID == ob.ID
                              select cs.Amount).FirstOrDefault(),
                     Currency = (from c in entities.Currency
                                 where c.ID == ob.CurrencyID
                                 select new Contract.Currency()
                                 {
                                     ID = c.ID,
                                     Name = c.Name.Trim(),
                                     Code = c.Code.Trim()
                                 }).FirstOrDefault(),
                     Intergral = ob.Intergral,
                     利润 = ob.TotalProfit
                 }).ToList();

            return (from t in otherOrderList
                    orderby t.Customer, t.Ref
                    select t).ToList();
        }

        public List<Contract.自组团支付单> GetTPOrder()
        {
            List<Contract.自组团支付单> otherOrderList =
                (from tp in entities.TouringParty
                 where tp.Status.Trim() == "完成" &&
                       tp.CustomerStatus.Trim() != "已收款"
                 select new Contract.自组团支付单()
                 {
                     ID = tp.ID,
                     Ref = tp.Ref.Trim(),
                     Type = "其他",
                     Name = tp.Name.Trim(),
                     Remark = tp.Remark.Trim(),
                     Customer = (from c in entities.Customer
                                 where c.ID == tp.CustomerID
                                 select c.Name.Trim()).FirstOrDefault(),
                     CustomerID = tp.CustomerID,
                     OrderUser = (from u in entities.User
                                  where u.ID == tp.OrderUserID
                                  select u.Staff.Trim()).FirstOrDefault(),
                     OrderDate = tp.OrderDate,
                     Money = tp.TotalPrice,
                     应付 = tp.TotalVendorPrice,
                     已支付金额 = (from cs in entities.CustomerSettlement
                              where cs.SourceID == tp.ID
                              select cs.Amount).FirstOrDefault(),
                     Currency = (from c in entities.Currency
                                 where c.Code == "CNY"
                                 select new Contract.Currency()
                                 {
                                     ID = c.ID,
                                     Name = c.Name.Trim(),
                                     Code = c.Code.Trim()
                                 }).FirstOrDefault(),
                     Intergral = 0,
                     利润 = tp.TotalProfit
                 }).ToList();

            return (from t in otherOrderList
                    orderby t.Customer, t.Ref
                    select t).ToList();
        }

        public List<Contract.Order> GetOrdersByCustomer(Contract.Customer customer)
        {
            List<Contract.Order> resultList = new List<Contract.Order>();

            List<Contract.Order> flightOrderList =
                (from fo in entities.FlightOrder
                 where fo.CustomerID == customer.ID &&
                       fo.Status.Trim() != "已作废" &&
                       fo.CustomerStatus.Trim() == "未付款"
                 select new Contract.Order()
                 {
                     ID = fo.ID,
                     Ref = fo.Ref,
                     OrderType = "飞机票",
                     OrderUserText = (from u in entities.User
                                      where u.ID == fo.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = fo.OrderDate,
                     Money = fo.TotalAccountReceivable,
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == fo.CurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = fo.Remark,
                     CustomerStatus = fo.CustomerStatus,
                     Intergral = fo.TotalIntergral
                 }).ToList();
            resultList.AddRange(flightOrderList);

            List<Contract.Order> flightOrderList1 =
                (from fo in entities.FlightOrder
                 where fo.CustomerID == customer.ID &&
                       fo.Status.Trim() != "已作废" &&
                       fo.CustomerStatus.Trim() == "部分收款"
                 select new Contract.Order()
                 {
                     ID = fo.ID,
                     Ref = fo.Ref,
                     OrderType = "飞机票",
                     OrderUserText = (from u in entities.User
                                      where u.ID == fo.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = fo.OrderDate,
                     Money = fo.TotalAccountReceivable -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == fo.ID
                             select cs.Amount).FirstOrDefault(),
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == fo.CurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = fo.Remark,
                     CustomerStatus = fo.CustomerStatus,
                     Intergral = fo.TotalIntergral
                 }).ToList();
            resultList.AddRange(flightOrderList1);

            List<Contract.Order> flightChangeList =
                (from fc in entities.FlightChange
                 where fc.CustomerID == customer.ID &&
                       fc.CustomerStatus.Trim() == "未付款"
                 select new Contract.Order()
                 {
                     ID = fc.ID,
                     Ref = fc.Ref,
                     OrderType = "飞机票改票",
                     OrderUserText = (from u in entities.User
                                      where u.ID == fc.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = fc.OrderDate,
                     Money = fc.Price,
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == fc.CurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = fc.Remark,
                     CustomerStatus = fc.CustomerStatus,
                 }).ToList();
            resultList.AddRange(flightChangeList);

            List<Contract.Order> flightChangeList1 =
                (from fc in entities.FlightChange
                 where fc.CustomerID == customer.ID &&
                       fc.CustomerStatus.Trim() == "部分收款"
                 select new Contract.Order()
                 {
                     ID = fc.ID,
                     Ref = fc.Ref,
                     OrderType = "飞机票改票",
                     OrderUserText = (from u in entities.User
                                      where u.ID == fc.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = fc.OrderDate,
                     Money = fc.Price -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == fc.ID
                             select cs.Amount).FirstOrDefault(),
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == fc.CurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = fc.Remark,
                     CustomerStatus = fc.CustomerStatus,
                 }).ToList();
            resultList.AddRange(flightChangeList1);

            List<Contract.Order> flightReturnList =
               (from fr in entities.FlightReturn
                where fr.CustomerID == customer.ID &&
                      fr.CustomerStatus.Trim() == "未付款"
                select new Contract.Order()
                {
                    ID = fr.ID,
                    Ref = fr.Ref,
                    OrderType = "飞机票退票",
                    OrderUserText = (from u in entities.User
                                     where u.ID == fr.OrderUserID
                                     select u.Staff).FirstOrDefault(),
                    OrderDate = fr.OrderDate,
                    Money = fr.CustomerReturnPrice,
                    MoneyCurrency = (from c in entities.Currency
                                     where c.ID == fr.CurrencyID
                                     select new Contract.Currency()
                                     {
                                         ID = c.ID,
                                         Name = c.Name,
                                         Code = c.Code
                                     }).FirstOrDefault(),
                    Remark = fr.Remark,
                    Intergral = fr.Intergral,
                    CustomerStatus = fr.CustomerStatus,
                }).ToList();
            resultList.AddRange(flightReturnList);

            List<Contract.Order> flightReturnList1 =
               (from fr in entities.FlightReturn
                where fr.CustomerID == customer.ID &&
                      fr.CustomerStatus.Trim() == "部分收款"
                select new Contract.Order()
                {
                    ID = fr.ID,
                    Ref = fr.Ref,
                    OrderType = "飞机票退票",
                    OrderUserText = (from u in entities.User
                                     where u.ID == fr.OrderUserID
                                     select u.Staff).FirstOrDefault(),
                    OrderDate = fr.OrderDate,
                    Money = fr.CustomerReturnPrice -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == fr.ID
                             select cs.Amount).FirstOrDefault(),
                    MoneyCurrency = (from c in entities.Currency
                                     where c.ID == fr.CurrencyID
                                     select new Contract.Currency()
                                     {
                                         ID = c.ID,
                                         Name = c.Name,
                                         Code = c.Code
                                     }).FirstOrDefault(),
                    Remark = fr.Remark,
                    Intergral = fr.Intergral,
                    CustomerStatus = fr.CustomerStatus,
                }).ToList();
            resultList.AddRange(flightReturnList1);

            List<Contract.Order> trainTicketOrderList =
               (from tto in entities.TrainTicketOrder
                where tto.CustomerID == customer.ID &&
                      tto.Status.Trim() != "已作废" &&
                      tto.CustomerStatus.Trim() == "未付款"
                select new Contract.Order()
                {
                    ID = tto.ID,
                    Ref = tto.Ref,
                    OrderType = "火车票",
                    OrderUserText = (from u in entities.User
                                     where u.ID == tto.OrderUserID
                                     select u.Staff).FirstOrDefault(),
                    OrderDate = tto.OrderDate,
                    Money = tto.TotalPrice,
                    MoneyCurrency = (from c in entities.Currency
                                     where c.ID == tto.CurrencyID
                                     select new Contract.Currency()
                                     {
                                         ID = c.ID,
                                         Name = c.Name,
                                         Code = c.Code
                                     }).FirstOrDefault(),
                    Remark = tto.Remark,
                    CustomerStatus = tto.CustomerStatus
                }).ToList();
            resultList.AddRange(trainTicketOrderList);

            List<Contract.Order> trainTicketOrderList1 =
              (from tto in entities.TrainTicketOrder
               where tto.CustomerID == customer.ID &&
                     tto.Status.Trim() != "已作废" &&
                     tto.CustomerStatus.Trim() == "部分收款"
               select new Contract.Order()
               {
                   ID = tto.ID,
                   Ref = tto.Ref,
                   OrderType = "火车票",
                   OrderUserText = (from u in entities.User
                                    where u.ID == tto.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = tto.OrderDate,
                   Money = tto.TotalPrice -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == tto.ID
                             select cs.Amount).FirstOrDefault(),
                   MoneyCurrency = (from c in entities.Currency
                                    where c.ID == tto.CurrencyID
                                    select new Contract.Currency()
                                    {
                                        ID = c.ID,
                                        Name = c.Name,
                                        Code = c.Code
                                    }).FirstOrDefault(),
                   Remark = tto.Remark,
                   CustomerStatus = tto.CustomerStatus
               }).ToList();
            resultList.AddRange(trainTicketOrderList1);

            List<Contract.Order> trainTicketReturnList =
              (from ttr in entities.TrainTicketReturn
               where ttr.CustomerID == customer.ID &&
                     ttr.CustomerStatus.Trim() == "未付款"
               select new Contract.Order()
               {
                   ID = ttr.ID,
                   Ref = ttr.Ref,
                   OrderType = "火车票退票",
                   OrderUserText = (from u in entities.User
                                    where u.ID == ttr.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = ttr.OrderDate,
                   Money = ttr.CustomerReturn,
                   MoneyCurrency = (from c in entities.Currency
                                    where c.ID == ttr.CurrencyID
                                    select new Contract.Currency()
                                    {
                                        ID = c.ID,
                                        Name = c.Name,
                                        Code = c.Code
                                    }).FirstOrDefault(),
                   CustomerStatus = ttr.CustomerStatus
               }).ToList();
            resultList.AddRange(trainTicketReturnList);

            List<Contract.Order> trainTicketReturnList1 =
             (from ttr in entities.TrainTicketReturn
              where ttr.CustomerID == customer.ID &&
                    ttr.CustomerStatus.Trim() == "部分收款"
              select new Contract.Order()
              {
                  ID = ttr.ID,
                  Ref = ttr.Ref,
                  OrderType = "火车票退票",
                  OrderUserText = (from u in entities.User
                                   where u.ID == ttr.OrderUserID
                                   select u.Staff).FirstOrDefault(),
                  OrderDate = ttr.OrderDate,
                  Money = ttr.CustomerReturn -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == ttr.ID
                             select cs.Amount).FirstOrDefault(),
                  MoneyCurrency = (from c in entities.Currency
                                   where c.ID == ttr.CurrencyID
                                   select new Contract.Currency()
                                   {
                                       ID = c.ID,
                                       Name = c.Name,
                                       Code = c.Code
                                   }).FirstOrDefault(),
                  CustomerStatus = ttr.CustomerStatus
              }).ToList();
            resultList.AddRange(trainTicketReturnList1);

            List<Contract.Order> hotelBookingList =
              (from hb in entities.HotelBooking
               where hb.CustomerID == customer.ID &&
                     hb.PaymentType == "预付" &&
                     hb.Status.Trim() != "已作废" &&
                     hb.CustomerStatus.Trim() == "未付款"
               select new Contract.Order()
               {
                   ID = hb.ID,
                   Ref = hb.Ref,
                   OrderType = "酒店",
                   OrderUserText = (from u in entities.User
                                    where u.ID == hb.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = hb.OrderDate,
                   Money = hb.TotalPrice,
                   MoneyCurrency = (from c in entities.Currency
                                    where c.ID == hb.CurrencyID
                                    select new Contract.Currency()
                                    {
                                        ID = c.ID,
                                        Name = c.Name,
                                        Code = c.Code
                                    }).FirstOrDefault(),
                   CustomerStatus = hb.CustomerStatus,
                   Intergral = hb.Intergral,
               }).ToList();
            resultList.AddRange(hotelBookingList);

            List<Contract.Order> hotelBookingList1 =
             (from hb in entities.HotelBooking
              where hb.CustomerID == customer.ID &&
                    hb.PaymentType == "预付" &&
                    hb.Status.Trim() != "已作废" &&
                    hb.CustomerStatus.Trim() == "部分收款"
              select new Contract.Order()
              {
                  ID = hb.ID,
                  Ref = hb.Ref,
                  OrderType = "酒店",
                  OrderUserText = (from u in entities.User
                                   where u.ID == hb.OrderUserID
                                   select u.Staff).FirstOrDefault(),
                  OrderDate = hb.OrderDate,
                  Money = hb.TotalPrice -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == hb.ID
                             select cs.Amount).FirstOrDefault(),
                  MoneyCurrency = (from c in entities.Currency
                                   where c.ID == hb.CurrencyID
                                   select new Contract.Currency()
                                   {
                                       ID = c.ID,
                                       Name = c.Name,
                                       Code = c.Code
                                   }).FirstOrDefault(),
                  CustomerStatus = hb.CustomerStatus,
                  Intergral = hb.Intergral
              }).ToList();
            resultList.AddRange(hotelBookingList1);

            List<Contract.Order> otherBusinessList =
              (from ob in entities.OtherBusiness
               where ob.CustomerID == customer.ID &&
                     ob.Status.Trim() != "已作废" &&
                     ob.CustomerStatus.Trim() == "未付款"
               select new Contract.Order()
               {
                   ID = ob.ID,
                   Ref = ob.Ref,
                   OrderType = "其他",
                   OrderUserText = (from u in entities.User
                                    where u.ID == ob.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = ob.OrderDate,
                   Money = ob.TotalPrice,
                   MoneyCurrency = (from c in entities.Currency
                                    where c.ID == ob.CurrencyID
                                    select new Contract.Currency()
                                    {
                                        ID = c.ID,
                                        Name = c.Name,
                                        Code = c.Code
                                    }).FirstOrDefault(),
                   CustomerStatus = ob.CustomerStatus,
                   Intergral = ob.Intergral
               }).ToList();
            resultList.AddRange(otherBusinessList);

            List<Contract.Order> otherBusinessList1 =
              (from ob in entities.OtherBusiness
               where ob.CustomerID == customer.ID &&
                     ob.Status.Trim() != "已作废" &&
                     ob.CustomerStatus.Trim() == "部分收款"
               select new Contract.Order()
               {
                   ID = ob.ID,
                   Ref = ob.Ref,
                   OrderType = "其他",
                   OrderUserText = (from u in entities.User
                                    where u.ID == ob.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = ob.OrderDate,
                   Money = ob.TotalPrice -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == ob.ID
                             select cs.Amount).FirstOrDefault(),
                   MoneyCurrency = (from c in entities.Currency
                                    where c.ID == ob.CurrencyID
                                    select new Contract.Currency()
                                    {
                                        ID = c.ID,
                                        Name = c.Name,
                                        Code = c.Code
                                    }).FirstOrDefault(),
                   CustomerStatus = ob.CustomerStatus,
                   Intergral = ob.Intergral
               }).ToList();
            resultList.AddRange(otherBusinessList1);

            List<Contract.Order> tourPartyList =
             (from ob in entities.TouringParty
              where ob.CustomerID == customer.ID &&
                    ob.CustomerStatus.Trim() == "未付款"
              select new Contract.Order()
              {
                  ID = ob.ID,
                  Ref = ob.Ref,
                  OrderType = "自组团",
                  OrderUserText = (from u in entities.User
                                   where u.ID == ob.OrderUserID
                                   select u.Staff).FirstOrDefault(),
                  OrderDate = ob.OrderDate,
                  Money = ob.TotalPrice,
                  CustomerStatus = ob.CustomerStatus,
                  Intergral = 0
              }).ToList();
            resultList.AddRange(otherBusinessList);

            List<Contract.Order> tourPartyList1 =
              (from ob in entities.TouringParty
               where ob.CustomerID == customer.ID &&
                     ob.CustomerStatus.Trim() == "部分收款"
               select new Contract.Order()
               {
                   ID = ob.ID,
                   Ref = ob.Ref,
                   OrderType = "其他",
                   OrderUserText = (from u in entities.User
                                    where u.ID == ob.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = ob.OrderDate,
                   Money = ob.TotalPrice -
                            (from cs in entities.CustomerSettlement
                             where cs.SourceID == ob.ID
                             select cs.Amount).FirstOrDefault(),
                   CustomerStatus = ob.CustomerStatus,
                   Intergral = 0
               }).ToList();
            resultList.AddRange(tourPartyList1);

            return resultList.OrderBy(o => o.OrderDate).ToList();
        }

        private void checkVendorOtherSettlement(Contract.VendorOtherSettlement vendorSettlement)
        {
            vendorSettlement.CheckNo = vendorSettlement.CheckNo.Trim();
            vendorSettlement.PaymentType = vendorSettlement.PaymentType.Trim();
            vendorSettlement.Remark = vendorSettlement.Remark.Trim();

            if (vendorSettlement.Vendor == null)
                throw new BusinessException(VerificationText.请输入供应商);
            if (vendorSettlement.PaymentType != "现金" && vendorSettlement.BankAccount == null)
                throw new BusinessException(VerificationText.请输入银行账户);
            if (vendorSettlement.PaymentType == string.Empty)
                throw new BusinessException(VerificationText.请输入毅丰支付方式);
            if (vendorSettlement.PostingDate == DateTime.MinValue)
                throw new BusinessException(VerificationText.请输入过账日期);
        }

        private void checkVendorSettlement(Contract.VendorSettlement vendorSettlement)
        {
            vendorSettlement.CheckNo = vendorSettlement.CheckNo.Trim();
            vendorSettlement.PaymentType = vendorSettlement.PaymentType.Trim();
            vendorSettlement.Remark = vendorSettlement.Remark.Trim();

            if (vendorSettlement.PaymentType != "现金" && vendorSettlement.BankAccount == null)
                throw new BusinessException(VerificationText.请输入银行账户);
            if (vendorSettlement.PaymentType == string.Empty)
                throw new BusinessException(VerificationText.请输入毅丰支付方式);
            if (vendorSettlement.PostingDate == DateTime.MinValue)
                throw new BusinessException(VerificationText.请输入过账日期);
        }

        public void VendorSettle(Contract.VendorOtherSettlement vendorSettlement)
        {
            checkVendorOtherSettlement(vendorSettlement);

            decimal totalMoney = 0;
            decimal money = vendorSettlement.Amount;
            foreach (Contract.Order order in vendorSettlement.OrderList)
                totalMoney += order.Money;

            BankAccount bankAccount = null;
            if (vendorSettlement.BankAccount != null)
                bankAccount = (from ba in entities.BankAccount
                               where ba.ID == vendorSettlement.BankAccount.ID
                               select ba).Single();

            if (vendorSettlement.PaymentType != "现金")
            {
                if (vendorSettlement.IsPay)
                    bankAccount.Amount -= money;
                else
                    bankAccount.Amount += money;
            }
            else
            {
                decimal cash = GetCash();
                if (vendorSettlement.IsPay)
                    SetCash(cash - money, false);
                else
                    SetCash(cash + money, false);
            }

            DateTime dateTime = DateTime.Now;

            foreach (Contract.Order order in vendorSettlement.OrderList)
            {
                if (money == 0 && vendorSettlement.Amount != 0)
                    break;

                VendorSettlement newVendorSettlement = new VendorSettlement();
                newVendorSettlement.ID = Guid.NewGuid();
                if (bankAccount == null)
                {
                    newVendorSettlement.BankAccountID = null;
                    newVendorSettlement.CurrencyID = order.MoneyCurrency.ID;
                }
                else
                {
                    newVendorSettlement.BankAccountID = bankAccount.ID;
                    newVendorSettlement.CurrencyID = bankAccount.CurrencyID;
                }
                newVendorSettlement.CheckNo = vendorSettlement.CheckNo;
                newVendorSettlement.VendorID = vendorSettlement.Vendor.ID;
                newVendorSettlement.PayType = vendorSettlement.PaymentType;
                newVendorSettlement.PostingDate = vendorSettlement.PostingDate;
                newVendorSettlement.Remark = vendorSettlement.Remark;
                //newVendorSettlement.ServiceCharge = vendorSettlement.ServiceCharge;
                //vendorSettlement.ServiceCharge = 0;
                newVendorSettlement.Ref = order.Ref;
                newVendorSettlement.Type = order.OrderType;
                newVendorSettlement.SourceID = order.ID;
                newVendorSettlement.PostingDate = vendorSettlement.PostingDate;
                newVendorSettlement.CurrencyID = vendorSettlement.Currency.ID;
                newVendorSettlement.ExchangeRate = vendorSettlement.ExchangeRate;

                decimal amount = (order.Money * vendorSettlement.ExchangeRate < money) ? order.Money : money / vendorSettlement.ExchangeRate;
                money -= amount;
                if (vendorSettlement.IsPay)
                    newVendorSettlement.Amount = amount;
                else
                    newVendorSettlement.Amount = 0 - amount;

                settleOrder(entities, order, amount, false, dateTime, 0);

                entities.AddToVendorSettlement(newVendorSettlement);
            }

            entities.SaveChanges();
        }

        public List<Contract.Order> GetHotelDiscountVendorOrders()
        {
            List<Contract.Order> resultList = new List<Contract.Order>();

            List<Contract.Order> hotelBookingList =
                (from hb in entities.HotelBooking
                 where hb.PaymentType.Trim() == "现付" &&
                       hb.Status.Trim() != "已作废" &&
                       hb.VendorStatus.Trim() == "未付款"
                 select new Contract.Order()
                 {
                     ID = hb.ID,
                     Ref = hb.Ref,
                     VendorText = (from v in entities.Vendor
                                   where v.ID == hb.VendorID
                                   select v.Name.Trim()).FirstOrDefault(),
                     OrderType = "酒店",
                     OrderUserText = (from u in entities.User
                                      where u.ID == hb.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = hb.OrderDate,
                     Money = hb.TotalProfit,
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == hb.VendorCurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = hb.Remark,
                     VendorStatus = hb.VendorStatus
                 }).ToList();
            resultList.AddRange(hotelBookingList);

            List<Contract.Order> hotelBookingList1 =
               (from hb in entities.HotelBooking
                where hb.PaymentType.Trim() == "现付" &&
                      hb.Status.Trim() != "已作废" &&
                      hb.VendorStatus.Trim() == "部分支付"
                select new Contract.Order()
                {
                    ID = hb.ID,
                    Ref = hb.Ref,
                    VendorText = (from v in entities.Vendor
                                  where v.ID == hb.VendorID
                                  select v.Name.Trim()).FirstOrDefault(),
                    OrderType = "酒店",
                    OrderUserText = (from u in entities.User
                                     where u.ID == hb.OrderUserID
                                     select u.Staff).FirstOrDefault(),
                    OrderDate = hb.OrderDate,
                    Money = hb.TotalProfit -
                            (from vc in entities.VendorSettlement
                             where vc.SourceID == hb.ID
                             select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
                    MoneyCurrency = (from c in entities.Currency
                                     where c.ID == hb.VendorCurrencyID
                                     select new Contract.Currency()
                                     {
                                         ID = c.ID,
                                         Name = c.Name,
                                         Code = c.Code
                                     }).FirstOrDefault(),
                    Remark = hb.Remark,
                    VendorStatus = hb.VendorStatus
                }).ToList();
            resultList.AddRange(hotelBookingList1);

            return resultList;
        }

        public List<Contract.Order> GetVendorOrders()
        {
            List<Contract.Order> resultList = new List<Contract.Order>();


            //List<Contract.Order> flightOrderList =
            //    (from fod in entities.FlightOrderDetail
            //     join fo in entities.FlightOrder on fod.FlightOrderID equals fo.ID
            //     where fod.VendorID == vendor.ID &&
            //           fo.Status.Trim() != "已作废" &&
            //           fod.VendorStatus.Trim() == "未付款"
            //     select new Contract.Order()
            //     {
            //         ID = fod.ID,
            //         Ref = fo.Ref,
            //         OrderType = "飞机票",
            //         OrderUserText = (from u in entities.User
            //                          where u.ID == fo.OrderUserID
            //                          select u.Staff).FirstOrDefault(),
            //         OrderDate = fo.OrderDate,
            //         Money = fod.AccountPayable,
            //         MoneyCurrency = (from c in entities.Currency
            //                          where c.ID == fod.VendorCurrencyID
            //                          select new Contract.Currency()
            //                          {
            //                              ID = c.ID,
            //                              Name = c.Name,
            //                              Code = c.Code
            //                          }).FirstOrDefault(),
            //         Remark = fod.Remark,
            //         VendorStatus = fod.VendorStatus
            //     }).ToList();
            //resultList.AddRange(flightOrderList);

            //List<Contract.Order> flightOrderList1 =
            //    (from fod in entities.FlightOrderDetail
            //     join fo in entities.FlightOrder on fod.FlightOrderID equals fo.ID
            //     where fod.VendorID == vendor.ID &&
            //           fo.Status.Trim() != "已作废" &&
            //           fod.VendorStatus.Trim() == "部分收款"
            //     select new Contract.Order()
            //     {
            //         ID = fo.ID,
            //         Ref = fo.Ref,
            //         OrderType = "飞机票",
            //         OrderUserText = (from u in entities.User
            //                          where u.ID == fo.OrderUserID
            //                          select u.Staff).FirstOrDefault(),
            //         OrderDate = fo.OrderDate,
            //         Money = fod.TotalAccountPayable -
            //                (from vc in entities.VendorSettlement
            //                 where vc.SourceID == fod.ID
            //                 select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
            //         MoneyCurrency = (from c in entities.Currency
            //                          where c.ID == fo.VendorCurrencyID
            //                          select new Contract.Currency()
            //                          {
            //                              ID = c.ID,
            //                              Name = c.Name,
            //                              Code = c.Code
            //                          }).FirstOrDefault(),
            //         Remark = fo.Remark,
            //         VendorStatus = fo.VendorStatus
            //     }).ToList();
            //resultList.AddRange(flightOrderList1);

            //List<Contract.Order> flightChangeList =
            //    (from fc in entities.FlightChange
            //     where fc.VendorID == vendor.ID &&
            //           fc.VendorStatus.Trim() == "未付款"
            //     select new Contract.Order()
            //     {
            //         ID = fc.ID,
            //         Ref = fc.Ref,
            //         OrderType = "飞机票改票",
            //         OrderUserText = (from u in entities.User
            //                          where u.ID == fc.OrderUserID
            //                          select u.Staff).FirstOrDefault(),
            //         OrderDate = fc.OrderDate,
            //         Money = fc.VendorPrice,
            //         MoneyCurrency = (from c in entities.Currency
            //                          where c.ID == fc.VendorCurrencyID
            //                          select new Contract.Currency()
            //                          {
            //                              ID = c.ID,
            //                              Name = c.Name,
            //                              Code = c.Code
            //                          }).FirstOrDefault(),
            //         Remark = fc.Remark,
            //         VendorStatus = fc.VendorStatus
            //     }).ToList();
            //resultList.AddRange(flightChangeList);

            //List<Contract.Order> flightChangeList1 =
            //   (from fc in entities.FlightChange
            //    where fc.VendorID == vendor.ID &&
            //          fc.VendorStatus.Trim() == "部分收款"
            //    select new Contract.Order()
            //    {
            //        ID = fc.ID,
            //        Ref = fc.Ref,
            //        OrderType = "飞机票改票",
            //        OrderUserText = (from u in entities.User
            //                         where u.ID == fc.OrderUserID
            //                         select u.Staff).FirstOrDefault(),
            //        OrderDate = fc.OrderDate,
            //        Money = fc.VendorPrice -
            //                (from vc in entities.VendorSettlement
            //                 where vc.SourceID == fc.ID
            //                 select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
            //        MoneyCurrency = (from c in entities.Currency
            //                         where c.ID == fc.VendorCurrencyID
            //                         select new Contract.Currency()
            //                         {
            //                             ID = c.ID,
            //                             Name = c.Name,
            //                             Code = c.Code
            //                         }).FirstOrDefault(),
            //        Remark = fc.Remark,
            //        VendorStatus = fc.VendorStatus
            //    }).ToList();
            //resultList.AddRange(flightChangeList1);

            //List<Contract.Order> flightReturnList =
            //    (from fc in entities.FlightChange
            //     where fc.VendorID == vendor.ID &&
            //           fc.VendorStatus.Trim() == "未付款"
            //     select new Contract.Order()
            //     {
            //         ID = fc.ID,
            //         Ref = fc.Ref,
            //         OrderType = "飞机票退票",
            //         OrderUserText = (from u in entities.User
            //                          where u.ID == fc.OrderUserID
            //                          select u.Staff).FirstOrDefault(),
            //         OrderDate = fc.OrderDate,
            //         Money = fc.VendorPrice,
            //         MoneyCurrency = (from c in entities.Currency
            //                          where c.ID == fc.VendorCurrencyID
            //                          select new Contract.Currency()
            //                          {
            //                              ID = c.ID,
            //                              Name = c.Name,
            //                              Code = c.Code
            //                          }).FirstOrDefault(),
            //         Remark = fc.Remark,
            //         VendorStatus = fc.VendorStatus
            //     }).ToList();
            //resultList.AddRange(flightReturnList);

            //List<Contract.Order> flightReturnList1 =
            //   (from fc in entities.FlightChange
            //    where fc.VendorID == vendor.ID &&
            //          fc.VendorStatus.Trim() == "部分支付"
            //    select new Contract.Order()
            //    {
            //        ID = fc.ID,
            //        Ref = fc.Ref,
            //        OrderType = "飞机票退票",
            //        OrderUserText = (from u in entities.User
            //                         where u.ID == fc.OrderUserID
            //                         select u.Staff).FirstOrDefault(),
            //        OrderDate = fc.OrderDate,
            //        Money = fc.VendorPrice -
            //                (from vc in entities.VendorSettlement
            //                 where vc.SourceID == fc.ID
            //                 select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
            //        MoneyCurrency = (from c in entities.Currency
            //                         where c.ID == fc.VendorCurrencyID
            //                         select new Contract.Currency()
            //                         {
            //                             ID = c.ID,
            //                             Name = c.Name,
            //                             Code = c.Code
            //                         }).FirstOrDefault(),
            //        Remark = fc.Remark,
            //        VendorStatus = fc.VendorStatus
            //    }).ToList();
            //resultList.AddRange(flightReturnList1);

            List<Contract.Order> trainTicketOrderList =
                (from tto in entities.TrainTicketOrder
                 where tto.Status.Trim() != "已作废" &&
                       tto.VendorStatus.Trim() == "未付款"
                 select new Contract.Order()
                 {
                     ID = tto.ID,
                     Ref = tto.Ref,
                     VendorText = (from v in entities.Vendor
                                   where v.ID == tto.VendorID
                                   select v.Name.Trim()).FirstOrDefault(),
                     OrderType = "火车票",
                     OrderUserText = (from u in entities.User
                                      where u.ID == tto.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = tto.OrderDate,
                     Money = tto.TotalVendorPrice,
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == tto.VendorCurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = tto.Remark,
                     VendorStatus = tto.VendorStatus
                 }).ToList();
            resultList.AddRange(trainTicketOrderList);

            List<Contract.Order> trainTicketOrderList1 =
                (from tto in entities.TrainTicketOrder
                 where tto.Status.Trim() != "已作废" &&
                       tto.VendorStatus.Trim() == "部分支付"
                 select new Contract.Order()
                 {
                     ID = tto.ID,
                     Ref = tto.Ref,
                     VendorText = (from v in entities.Vendor
                                   where v.ID == tto.VendorID
                                   select v.Name.Trim()).FirstOrDefault(),
                     OrderType = "火车票",
                     OrderUserText = (from u in entities.User
                                      where u.ID == tto.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = tto.OrderDate,
                     Money = tto.TotalVendorPrice -
                            (from vc in entities.VendorSettlement
                             where vc.SourceID == tto.ID
                             select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == tto.VendorCurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = tto.Remark,
                     VendorStatus = tto.VendorStatus
                 }).ToList();
            resultList.AddRange(trainTicketOrderList1);

            List<Contract.Order> trainTicketReturnList =
               (from ttr in entities.TrainTicketReturn
                where ttr.VendorStatus.Trim() == "未付款"
                select new Contract.Order()
                {
                    ID = ttr.ID,
                    Ref = ttr.Ref,
                    VendorText = (from v in entities.Vendor
                                  where v.ID == ttr.VendorID
                                  select v.Name.Trim()).FirstOrDefault(),
                    OrderType = "火车票退票",
                    OrderUserText = (from u in entities.User
                                     where u.ID == ttr.OrderUserID
                                     select u.Staff).FirstOrDefault(),
                    OrderDate = ttr.OrderDate,
                    Money = ttr.VendorReturn,
                    MoneyCurrency = (from c in entities.Currency
                                     where c.ID == ttr.VendorCurrencyID
                                     select new Contract.Currency()
                                     {
                                         ID = c.ID,
                                         Name = c.Name,
                                         Code = c.Code
                                     }).FirstOrDefault(),
                    VendorStatus = ttr.VendorStatus
                }).ToList();
            resultList.AddRange(trainTicketReturnList);

            List<Contract.Order> trainTicketReturnList1 =
              (from ttr in entities.TrainTicketReturn
               where ttr.VendorStatus.Trim() == "部分支付"
               select new Contract.Order()
               {
                   ID = ttr.ID,
                   Ref = ttr.Ref,
                   VendorText = (from v in entities.Vendor
                                 where v.ID == ttr.VendorID
                                 select v.Name.Trim()).FirstOrDefault(),
                   OrderType = "火车票退票",
                   OrderUserText = (from u in entities.User
                                    where u.ID == ttr.OrderUserID
                                    select u.Staff).FirstOrDefault(),
                   OrderDate = ttr.OrderDate,
                   Money = ttr.VendorReturn -
                            (from vc in entities.VendorSettlement
                             where vc.SourceID == ttr.ID
                             select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
                   MoneyCurrency = (from c in entities.Currency
                                    where c.ID == ttr.VendorCurrencyID
                                    select new Contract.Currency()
                                    {
                                        ID = c.ID,
                                        Name = c.Name,
                                        Code = c.Code
                                    }).FirstOrDefault(),
                   VendorStatus = ttr.VendorStatus
               }).ToList();
            resultList.AddRange(trainTicketReturnList1);

            List<Contract.Order> hotelBookingList =
                (from hb in entities.HotelBooking
                 where hb.PaymentType.Trim() == "预付" &&
                       hb.Status.Trim() != "已作废" &&
                       hb.VendorStatus.Trim() == "未付款"
                 select new Contract.Order()
                 {
                     ID = hb.ID,
                     Ref = hb.Ref,
                     VendorText = (from v in entities.Vendor
                                   where v.ID == hb.VendorID
                                   select v.Name.Trim()).FirstOrDefault(),
                     OrderType = "酒店",
                     OrderUserText = (from u in entities.User
                                      where u.ID == hb.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = hb.OrderDate,
                     Money = hb.TotalVendorPrice,
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == hb.VendorCurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = hb.Remark,
                     VendorStatus = hb.VendorStatus
                 }).ToList();
            resultList.AddRange(hotelBookingList);

            List<Contract.Order> hotelBookingList1 =
               (from hb in entities.HotelBooking
                where hb.PaymentType.Trim() == "预付" &&
                      hb.Status.Trim() != "已作废" &&
                      hb.VendorStatus.Trim() == "部分支付"
                select new Contract.Order()
                {
                    ID = hb.ID,
                    Ref = hb.Ref,
                    VendorText = (from v in entities.Vendor
                                  where v.ID == hb.VendorID
                                  select v.Name.Trim()).FirstOrDefault(),
                    OrderType = "酒店",
                    OrderUserText = (from u in entities.User
                                     where u.ID == hb.OrderUserID
                                     select u.Staff).FirstOrDefault(),
                    OrderDate = hb.OrderDate,
                    Money = hb.TotalVendorPrice -
                            (from vc in entities.VendorSettlement
                             where vc.SourceID == hb.ID
                             select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
                    MoneyCurrency = (from c in entities.Currency
                                     where c.ID == hb.VendorCurrencyID
                                     select new Contract.Currency()
                                     {
                                         ID = c.ID,
                                         Name = c.Name,
                                         Code = c.Code
                                     }).FirstOrDefault(),
                    Remark = hb.Remark,
                    VendorStatus = hb.VendorStatus
                }).ToList();
            resultList.AddRange(hotelBookingList1);

            List<Contract.Order> otherBusinessList =
                (from hb in entities.OtherBusiness
                 where hb.Status.Trim() != "已作废" &&
                       hb.VendorStatus.Trim() == "未付款"
                 select new Contract.Order()
                 {
                     ID = hb.ID,
                     Ref = hb.Ref,
                     VendorText = (from v in entities.Vendor
                                   where v.ID == hb.VendorID
                                   select v.Name.Trim()).FirstOrDefault(),
                     OrderType = "其他",
                     OrderUserText = (from u in entities.User
                                      where u.ID == hb.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = hb.OrderDate,
                     Money = hb.TotalVendorPrice,
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == hb.CurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = hb.Remark,
                     VendorStatus = hb.VendorStatus
                 }).ToList();
            resultList.AddRange(otherBusinessList);

            List<Contract.Order> otherBusinessList1 =
                (from ob in entities.OtherBusiness
                 where ob.Status.Trim() != "已作废" &&
                       ob.VendorStatus.Trim() == "部分支付"
                 select new Contract.Order()
                 {
                     ID = ob.ID,
                     Ref = ob.Ref,
                     VendorText = (from v in entities.Vendor
                                   where v.ID == ob.VendorID
                                   select v.Name.Trim()).FirstOrDefault(),
                     OrderType = "其他",
                     OrderUserText = (from u in entities.User
                                      where u.ID == ob.OrderUserID
                                      select u.Staff).FirstOrDefault(),
                     OrderDate = ob.OrderDate,
                     Money = ob.TotalVendorPrice -
                            (from vc in entities.VendorSettlement
                             where vc.SourceID == ob.ID
                             select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
                     MoneyCurrency = (from c in entities.Currency
                                      where c.ID == ob.CurrencyID
                                      select new Contract.Currency()
                                      {
                                          ID = c.ID,
                                          Name = c.Name,
                                          Code = c.Code
                                      }).FirstOrDefault(),
                     Remark = ob.Remark,
                     VendorStatus = ob.VendorStatus
                 }).ToList();
            resultList.AddRange(otherBusinessList1);

            //List<Contract.Order> insurancePolicyList =
            //    (from ip in entities.InsurancePolicy
            //     where ip.VendorID == vendor.ID &&
            //           ip.Status.Trim() == "已用" &&
            //           ip.VendorStatus.Trim() == "未付款"
            //     select new Contract.Order()
            //     {
            //         ID = ip.ID,
            //         Ref = ip.Ref,
            //         OrderType = "飞机票",
            //         OrderUserText = (from u in entities.User
            //                          where u.ID == ip.OrderUserID.Value
            //                          select u.Staff).FirstOrDefault(),
            //         OrderDate = ip.OrderDate,
            //         Money = ip.BasePrice,
            //         MoneyCurrency = (from c in entities.Currency
            //                          where c.ID == ip.CurrencyID
            //                          select new Contract.Currency()
            //                          {
            //                              ID = c.ID,
            //                              Name = c.Name,
            //                              Code = c.Code
            //                          }).FirstOrDefault(),
            //         VendorStatus = ip.VendorStatus
            //     }).ToList();
            //resultList.AddRange(insurancePolicyList);

            //List<Contract.Order> insurancePolicyList1 =
            //    (from ip in entities.InsurancePolicy
            //     where ip.VendorID == vendor.ID &&
            //           ip.Status.Trim() == "已用" &&
            //           ip.VendorStatus.Trim() == "部分支付"
            //     select new Contract.Order()
            //     {
            //         ID = ip.ID,
            //         Ref = ip.Ref,
            //         OrderType = "飞机票",
            //         OrderUserText = (from u in entities.User
            //                          where u.ID == ip.OrderUserID.Value
            //                          select u.Staff).FirstOrDefault(),
            //         OrderDate = ip.OrderDate,
            //         Money = ip.BasePrice -
            //                (from vc in entities.VendorSettlement
            //                 where vc.SourceID == ip.ID
            //                 select vc.Amount * vc.ExchangeRate).FirstOrDefault(),
            //         MoneyCurrency = (from c in entities.Currency
            //                          where c.ID == ip.CurrencyID
            //                          select new Contract.Currency()
            //                          {
            //                              ID = c.ID,
            //                              Name = c.Name,
            //                              Code = c.Code
            //                          }).FirstOrDefault(),
            //         VendorStatus = ip.VendorStatus
            //     }).ToList();
            //resultList.AddRange(insurancePolicyList1);

            return resultList.OrderBy(o => o.OrderDate).ToList();
        }

        public List<Contract.VendorSettlement> GetVendorSettlementByDate(DateTime startDate, DateTime endDate)
        {
            startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day);
            endDate = new DateTime(endDate.Year, endDate.Month, endDate.Day).AddDays(1).AddMilliseconds(-5);

            var vsList = (from vs in entities.VendorSettlement
                          where vs.PostingDate >= startDate &&
                                vs.PostingDate <= endDate
                          select new Contract.VendorSettlement()
                          {
                              ID = vs.ID,
                              Amount = vs.Amount,
                              BankAccountID = vs.BankAccountID,
                              CheckNo = vs.CheckNo,
                              Currency = new Contract.Currency() { ID = vs.CurrencyID },
                              ExchangeRate = vs.ExchangeRate,
                              PaymentType = vs.PayType.Trim(),
                              OrderRef = vs.Ref.Trim(),
                              OrderType = vs.Type.Trim(),
                              Vendor = new Contract.Vendor() { ID = vs.VendorID },
                              Remark = vs.Remark.Trim(),
                              PostingDate = vs.PostingDate,
                          }).ToList();

            foreach (Contract.VendorSettlement cVendorSettlement in vsList)
            {
                cVendorSettlement.Currency = new BaseBL().GetCurrencyByID(cVendorSettlement.Currency.ID);
                cVendorSettlement.Vendor = new MasterBL().GetVendorByID(cVendorSettlement.Vendor.ID);

                if (cVendorSettlement.BankAccountID != null)
                    cVendorSettlement.BankAccount = new MasterBL().GetBankAccountByID(cVendorSettlement.BankAccountID.Value);
            }

            return vsList;
        }

        public void UpdateVendorSettlementList(List<Contract.VendorSettlement> vendorSettlementList)
        {
            foreach (Contract.VendorSettlement cVendorSettlement in vendorSettlementList)
            {
                VendorSettlement vendorSettlement = (from vs in entities.VendorSettlement
                                                     where vs.ID == cVendorSettlement.ID
                                                     select vs).SingleOrDefault();

                BankAccount oldBankAccount = vendorSettlement.BankAccount;
                if (oldBankAccount != null)
                    oldBankAccount.Amount += cVendorSettlement.Amount;

                if (cVendorSettlement.BankAccount != null)
                {
                    BankAccount newBankAccount = (from vs in entities.BankAccount
                                                  where vs.ID == cVendorSettlement.BankAccount.ID
                                                  select vs).SingleOrDefault();

                    newBankAccount.Amount -= cVendorSettlement.Amount;
                }

                vendorSettlement.BankAccountID = cVendorSettlement.BankAccount.ID;
                vendorSettlement.PayType = cVendorSettlement.PaymentType;
                vendorSettlement.CheckNo = cVendorSettlement.CheckNo;
            }

            entities.SaveChanges();
        }

        public void Transfer(Contract.AccountTransfer accountTransfer)
        {
            checkAccountTransfer(accountTransfer);


            AmountTransfer amountTransfer = new AmountTransfer();
            amountTransfer.ID = accountTransfer.ID;
            amountTransfer.ReceiveDate = accountTransfer.ReceiveDate;
            amountTransfer.ServiceCharge = accountTransfer.ServiceCharge;
            amountTransfer.SourceID = accountTransfer.Source.ID;
            amountTransfer.TargetID = accountTransfer.Target.ID;
            amountTransfer.TransferDate = accountTransfer.TransferDate;
            amountTransfer.Amount = accountTransfer.Amount;
            entities.AddToAmountTransfer(amountTransfer);

            BankAccount soureceBankAccount = (from ba in entities.BankAccount
                                              where ba.ID == amountTransfer.SourceID
                                              select ba).Single();
            BankAccount targetBankAccount = (from ba in entities.BankAccount
                                             where ba.ID == amountTransfer.TargetID
                                             select ba).Single();
            soureceBankAccount.Amount -= (accountTransfer.Amount + accountTransfer.ServiceCharge);
            targetBankAccount.Amount += accountTransfer.Amount * accountTransfer.ExcehangeRate;

            entities.SaveChanges();

        }

        private void checkAccountTransfer(Contract.AccountTransfer accountTransfer)
        {
            if (accountTransfer.TransferDate == DateTime.MinValue)
                throw new BusinessException(VerificationText.请输入转账日期);
            if (accountTransfer.ReceiveDate == DateTime.MinValue)
                throw new BusinessException(VerificationText.请输入到账日期);
            if (accountTransfer.Amount <= 0)
                throw new BusinessException(VerificationText.请输入正确的转账金额);
            if (accountTransfer.Source == null)
                throw new BusinessException(VerificationText.请输入转出账户);
            if (accountTransfer.Target == null)
                throw new BusinessException(VerificationText.请输入转入账户);
            if (accountTransfer.Source.Currency != accountTransfer.Target.Currency && accountTransfer.ExcehangeRate == 0)
                throw new BusinessException(VerificationText.请输入汇率);
        }

        public void Payment(Contract.OtherPayment otherPayment)
        {
            checkOtherPayment(otherPayment);


            OtherPayment newOtherPayment = new OtherPayment();
            newOtherPayment.ID = otherPayment.ID;
            newOtherPayment.Amount = otherPayment.Amount;
            
            newOtherPayment.Content = otherPayment.Content;
            newOtherPayment.Type = otherPayment.Type;
            newOtherPayment.Date = otherPayment.Date;
            newOtherPayment.Remark = otherPayment.Remark;

            entities.AddToOtherPayment(newOtherPayment);

            if (otherPayment.BankAccount != null)
            {
                newOtherPayment.BankAccountID = otherPayment.BankAccount.ID;
                BankAccount bankAccount = (from ba in entities.BankAccount
                                           where ba.ID == newOtherPayment.BankAccountID
                                           select ba).Single();
                bankAccount.Amount -= otherPayment.Amount;
            }

            entities.SaveChanges();
        }

        private void checkOtherPayment(Contract.OtherPayment otherPayment)
        {
            otherPayment.Content = otherPayment.Content.Trim();
            otherPayment.Type = otherPayment.Type.Trim();

            if (otherPayment.Content == string.Empty)
                throw new BusinessException(VerificationText.请输入支付项);
        }

        public void UpdateVendorSettle(Contract.VendorSettlement vendorSettlement)
        {
            checkVendorSettlement(vendorSettlement);

            VendorSettlement oldVendorSettlement = (from vs in entities.VendorSettlement
                                                    where vs.ID == vendorSettlement.ID
                                                    select vs).SingleOrDefault();
            if (oldVendorSettlement == null)
                throw new BusinessException(BusinessFail.找不到记录);

            if (oldVendorSettlement.BankAccount != null)
            {
                if (oldVendorSettlement.BankAccountID != vendorSettlement.BankAccount.ID)
                {
                    oldVendorSettlement.BankAccount.Amount += vendorSettlement.Amount;

                    BankAccount newBankAccount = (from b in entities.BankAccount
                                                  where b.ID == vendorSettlement.BankAccountID
                                                  select b).SingleOrDefault();
                    newBankAccount.Amount -= vendorSettlement.Amount;
                    if (newBankAccount.Amount < 0 && !newBankAccount.CanNegative)
                        throw new BusinessException(BusinessFail.余额不足);
                }
            }
            oldVendorSettlement.PayType = vendorSettlement.PaymentType;

            entities.SaveChanges();

        }

        public List<Contract.TourPartySettlement> GetPendingPayTouringParty()
        {
            List<Contract.TourPartySettlement> list =
                (from tp in entities.TouringParty
                 where tp.VendorStatus != "已支付"
                 orderby tp.Ref
                 select new Contract.TourPartySettlement()
                 {
                     ID = tp.ID,
                     Customer = (from c in entities.Customer
                                 where c.ID == tp.CustomerID
                                 select c.Name.Trim()).FirstOrDefault(),
                     Name = tp.Name.Trim(),
                     OrderDate = tp.OrderDate,
                     //PayedPrice = tp.TotalVendorPrice,
                     Ref = tp.Ref.Trim(),
                     TotalPrice = tp.TotalVendorPrice,
                     Status = tp.VendorStatus.Trim(),
                 }).ToList();

            foreach (Contract.TourPartySettlement tourPartySettlement in list)
            {
                if (tourPartySettlement.Status != "部分支付")
                    continue;

                tourPartySettlement.PayedDetail =
                    (from vs in entities.VendorSettlement
                     where vs.SourceID == tourPartySettlement.ID
                     orderby vs.PostingDate
                     select new Contract.TourPartySettlementDetail()
                     {
                         ID = vs.ID,
                         Price = vs.Amount,
                         Vendor = new Contract.RVendor() { ID = vs.VendorID }
                     }).ToList();

                foreach (Contract.TourPartySettlementDetail detail in tourPartySettlement.PayedDetail)
                    detail.Vendor = (from v in entities.Vendor
                                     where v.ID == detail.Vendor.ID
                                     select new Contract.RVendor()
                                     {
                                         ID = v.ID,
                                         Address = v.Address.Trim(),
                                         Effective = v.Effective,
                                         Name = v.Name.Trim(),
                                         Nr = v.Nr.Trim(),
                                         Remark = v.Remark.Trim(),
                                         ProjectList = (from vp in entities.VendorProject
                                                        join p in entities.Project on vp.ProjectID equals p.ID
                                                        where vp.VendorID == v.ID
                                                        select p.Name.Trim()).ToList()
                                     }).SingleOrDefault();
            }

            return list;
        }

        public void TourPartyVendorSettlement(Contract.TourPartySettlement settlement, List<Contract.VendorSettlement> payedList, bool isComplete)
        {
            TouringParty touringParty = (from tp in entities.TouringParty
                                         where tp.ID == settlement.ID
                                         select tp).SingleOrDefault();

            if (isComplete)
                touringParty.VendorStatus = "已支付";
            else
                touringParty.VendorStatus = "部分支付";

            List<BankAccount> bankAccountList = (from ba in entities.BankAccount
                                                 select ba).ToList();

            foreach (Contract.VendorSettlement vendorSettlement in payedList)
            {
                VendorSettlement dataVendorSettlement = new VendorSettlement();
                dataVendorSettlement.ID = vendorSettlement.ID;

                BankAccount bankAccount = (from ba in bankAccountList
                                           where ba.ID == vendorSettlement.BankAccountID
                                           select ba).SingleOrDefault();

                bankAccount.Amount -= vendorSettlement.Amount;

                if (bankAccount.Amount < 0 && !bankAccount.CanNegative)
                    throw new BusinessException(BusinessFail.余额不足);

                dataVendorSettlement.BankAccountID = vendorSettlement.BankAccount.ID;
                dataVendorSettlement.PayType = vendorSettlement.PaymentType.Trim();
                dataVendorSettlement.CheckNo = vendorSettlement.CheckNo;
                dataVendorSettlement.PostingDate = vendorSettlement.PostingDate;
                dataVendorSettlement.Ref = touringParty.Ref.Trim();
                dataVendorSettlement.Remark = vendorSettlement.Remark.Trim();
                dataVendorSettlement.SourceID = touringParty.ID;
                dataVendorSettlement.Type = "自组团";
                dataVendorSettlement.VendorID = vendorSettlement.Vendor.ID;

                entities.AddToVendorSettlement(dataVendorSettlement);
            }

            entities.SaveChanges();
        }

        public decimal GetCash()
        {
            var data = (from sd in entities.SystemData
                        where sd.Name == "Cash"
                        select sd).SingleOrDefault();
            if (data == null)
                return 0;
            else
                return Convert.ToDecimal(data.Value);
        }

        public void SetCash(decimal cash)
        {
            SetCash(cash, true);
        }

        public void SetCash(decimal cash , bool isSave)
        {
            var data = (from sd in entities.SystemData
                        where sd.Name == "Cash"
                        select sd).SingleOrDefault();
            if (data == null)
            {
                data = new SystemData();
                data.Name = "Cash";

                entities.AddToSystemData(data);
            }

            data.Value = cash.ToString();

            if (isSave)
                entities.SaveChanges();
        }

        #endregion
    }
}
